import { ToastController } from 'ionic-angular';
import { Component, ViewChild } from '@angular/core';
import { SplashScreen } from '@ionic-native/splash-screen';
import { StatusBar } from '@ionic-native/status-bar';
import { TranslateService } from '@ngx-translate/core';
import { Config, Nav, Platform, IonicApp, App } from 'ionic-angular';
import { MobileAccessibility } from '@ionic-native/mobile-accessibility';
import { FirstRunPage } from '../pages';
import { Settings } from '../providers';

import { MainPage } from '../pages';
import { BaseUI } from '../common/baseUI';

@Component({
  template: `<ion-nav #content [root]="rootPage"></ion-nav>`
})
export class MyApp extends BaseUI {
  backButtonPressed: boolean = false; //用于判断返回键是否触发
  rootPage = FirstRunPage;
  backPressed: boolean = false;

  @ViewChild(Nav) nav: Nav;

  pages: any[] = [
    { title: 'pc', component: 'PcPage' },
    { title: 'td', component: 'TdPage' },
    { title: 'wd', component: 'WdPage' }
  ];

  constructor(
    private translate: TranslateService,
    public platform: Platform,
    public ionicApp: IonicApp,
    settings: Settings,
    private config: Config,
    private statusBar: StatusBar,
    private splashScreen: SplashScreen,
    private appCtrl: App,
    private toastCtrl: ToastController,
    private mobileAccessibility: MobileAccessibility
  ) {
    super();
    platform.ready().then(() => {
      // Okay, so the platform is ready and our plugins are available.
      // Here you can do any higher level native things you might need.
      this.statusBar.styleDefault();
      // this.statusBar.styleLightContent();
      this.splashScreen.hide();
      this.mobileAccessibility.usePreferredTextZoom(false);
    });
    this.change();
    this.registerBackButtonAction();
    if (this.platform.is('android')) {
      // this.statusBar.backgroundColorByHexString('#00ffffff');
    }
  }

  change() {
    if (localStorage.getItem('token')) {
      this.rootPage = MainPage;
    } else {
      this.rootPage = FirstRunPage;
    }
  }

  initTranslate() {
    // Set the default language for translation strings, and the current language.
    this.translate.setDefaultLang('en');
    const browserLang = this.translate.getBrowserLang();

    if (browserLang) {
      if (browserLang === 'zh') {
        const browserCultureLang = this.translate.getBrowserCultureLang();

        if (browserCultureLang.match(/-CN|CHS|Hans/i)) {
          this.translate.use('zh-cmn-Hans');
        } else if (browserCultureLang.match(/-TW|CHT|Hant/i)) {
          this.translate.use('zh-cmn-Hant');
        }
      } else {
        this.translate.use(this.translate.getBrowserLang());
      }
    } else {
      this.translate.use('en'); // Set your language here
    }

    this.translate.get(['BACK_BUTTON_TEXT']).subscribe(values => {
      this.config.set('ios', 'backButtonText', values.BACK_BUTTON_TEXT);
    });
  }

  openPage(page) {
    // Reset the content nav to have just this page
    // we wouldn't want the back button to show in this scenario
    this.nav.setRoot(page.component);
  }

  //双击物理返回按钮退出程序
  registerBackButtonAction(): void {
    //物理按键的返回上一页
    this.platform.registerBackButtonAction(() => {
      //获取NavController
      let activeNav = this.appCtrl.getActiveNavs()[0];
      // 如果当前界面不是首页
      if (this.appCtrl.getActiveNav().getActive().id == 'PcPage') {
        this.showExit();
      }
      if (this.appCtrl.getActiveNav().getActive().id == 'TeamMyPage') {
        this.showExit();
      }
      if (this.appCtrl.getActiveNav().getActive().id == 'WdPage') {
        this.showExit();
      }
      if (this.appCtrl.getActiveNav().getActive().id == 'LoginOrRegisterPage') {
        this.showExit();
      }
      activeNav.pop();
    }, 0);
  }

  //退出应用方法
  showExit(): void {
    //如果为true，退出
    if (this.backPressed) {
      this.platform.exitApp();
    } else {
      //第一次弹出提示框
      super.showToast(this.toastCtrl, '再按一次退出应用');
      //标记为true
      this.backPressed = true;
      //两秒后标记为false，如果退出的话，就不会执行了
      setTimeout(() => (this.backPressed = false), 2000);
    }
  }
}

/**
 * Fix keyboard height.
 * */
let coordinateY;

let offsetY;

function tapCoordinates(event) {
  const viewPortHeight = window.innerHeight;

  coordinateY = event.touches[0].clientY;

  offsetY = viewPortHeight - coordinateY;
}

function keyboardShowHandler(event) {
  const keyboardHeight = event.keyboardHeight;

  const bodyMove = <HTMLElement>document.querySelector('ion-app');

  const bodyMoveStyle = bodyMove.style;

  const compensationHeight = 80;

  if (offsetY < keyboardHeight + compensationHeight) {
    bodyMoveStyle.top = -compensationHeight + 'px';

    bodyMoveStyle.height = window.innerHeight + compensationHeight + 'px';
  }
}

function keyboardHideHandler() {
  const removeStyles = <HTMLElement>document.querySelector('ion-app');

  removeStyles.removeAttribute('style');
}

window.addEventListener('native.keyboardshow', keyboardShowHandler);

window.addEventListener('native.keyboardhide', keyboardHideHandler);

window.addEventListener('touchstart', tapCoordinates);
